<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
    <title>Document</title>
    <style>
        .draggable{
            width:100px;
            height:100px;
            position: absolute;
            background-color: lightcoral;
            cursor: move;
        }
    </style>
</head>
<body>
    <div class="draggable" style="left:50px;top:50px;"></div>
    <div class="draggable" style="left:50px;top:200px;"></div>
    <div class="draggable" style="left:50px;top:350px;"></div>
    <script>
        //let draggables = document.querySelectorAll('.draggable');
        //当前正在拖拽的元素
        let currentDragging=null;
        //循环所有的元素，给每个元素都绑定 mousedown事件
       /*  draggables.forEach((draggable)=>{
            draggable.addEventListener('mousedown',(event)=>{
                //设置当前正在拖动的元素为draggable
                currentDragging=draggable;
                //把按下鼠标左键的时候，距离元素左则的偏移量记录元素的自定义属性集合对象上
                currentDragging.dataset.offsetX=event.offsetX;
                currentDragging.dataset.offsetY= event.offsetY;
            })
        }); */
        document.addEventListener('mousedown',(event)=>{
            const {target} = event;
            if(target.classList.contains('draggable')){
                //设置当前正在拖动的元素为draggable
                currentDragging=target;
                //把按下鼠标左键的时候，距离元素左则的偏移量记录元素的自定义属性集合对象上
                currentDragging.dataset.offsetX=event.offsetX;
                currentDragging.dataset.offsetY= event.offsetY;
            }
        })
        document.addEventListener('mousemove',(event)=>{
            //如果当前没有要拖动的元素就直接返回了
            if(!currentDragging)return;
            //如果当前有正在拖动的元素，就可以重新计算元素的位置了
            currentDragging.style.left = (event.clientX-currentDragging.dataset.offsetX)+'px';
            currentDragging.style.top = (event.clientY-currentDragging.dataset.offsetY)+'px'
        });
        document.addEventListener('mouseup',(event)=>{
            currentDragging=null;
        });
    </script>
</body>
</html>